package edcom.server;

import java.sql.*;

import edcom.client.Student;

public class StudentManager {
	
	public StudentManager()
	{
		
	}
	
	public void insertStudent(Student std) throws Exception {
		
		String statement = "INSERT INTO student VALUES (" +
			"'" + std.getStudentNumber() + "', " +
			"'" + std.getName() + "', " +
			"'" + std.getUserName() + "', " +
			"'" + std.getPassword() + "', " +
			"'" + std.getEmail() + "', " +
			"'" + std.getMajor() + "')";
		
		try {
			String connectionURL = "jdbc:mysql://localhost/edcom";
			Connection connection = null;
			Class.forName("com.mysql.jdbc.Driver").newInstance();
			connection = DriverManager.getConnection(connectionURL, "root", "durendal");
			if(!connection.isClosed()){
				boolean rs = false;
				PreparedStatement pstmt = ///*
						connection.prepareStatement(statement);
			    rs = pstmt.execute(); // try to execute the insert statement
			    if(rs == false);// throw new SQLInsertException("FALSE");
			    // if rs == false, insert is good
			}
			else
				throw new SQLSelectException("Connection failed.");
		} catch (ClassNotFoundException cnfe) {
			throw new SQLSelectException(cnfe.getMessage());
		} catch (SQLException sqle) {
			throw new SQLSelectException(sqle.getMessage());
		}
	}
	
	public boolean studentExists(Student std) throws SQLSelectException {
		
		
		throw new SQLSelectException("SQL Select Not Implemented");
	}
	
	public Student getStudentUsingLoginKeys(String UserName, String Password) 
			throws Exception {
		Student studentObject = null;
		
		try {
			String connectionURL = "jdbc:mysql://localhost/edcom";
			Connection connection = null;
			Class.forName("com.mysql.jdbc.Driver").newInstance();
			connection = DriverManager.getConnection(connectionURL, "root", "durendal");
			if(!connection.isClosed()){
				ResultSet rs = null;
				PreparedStatement pstmt = ///*
						connection.prepareStatement("SELECT * FROM student " +
						"WHERE username='" + UserName + "' AND password='" + 
						Password + "' "); // */
						//connection.prepareStatement("SELECT * FROM student");
			    rs = pstmt.executeQuery();
				///*
			    if(rs.wasNull() || (rs == null) || rs.isClosed()) 
			    	throw new SQLSelectException("Invalid inputs."); // */
				rs.next();
				studentObject = new Student();
				studentObject.setStudentNumber(rs.getString(1));
				studentObject.setName(rs.getString(2));
				studentObject.setUserName(rs.getString(3));
				studentObject.setPassword(rs.getString(4));
				studentObject.setEmail(rs.getString(5));
				studentObject.setMajor(rs.getString(6));
			}
			else
				throw new SQLSelectException("Connection failed.");
		} catch (ClassNotFoundException cnfe) {
			throw new SQLSelectException(cnfe.getMessage());
		} catch (SQLException sqle) {
			throw new SQLSelectException(sqle.getMessage());
		}
		
		return studentObject;
	}
}
